package com.xyrl.project.manager.core.shiro;

import com.xyrl.common.util.*;
import com.xyrl.project.common.authentication.JWTToken;
import com.xyrl.project.common.authentication.JWTUtil;
import com.xyrl.project.common.authentication.LoginInfo;
import com.xyrl.project.common.constant.XyrlConstant;
import com.xyrl.project.common.manager.UserManager;
import com.xyrl.project.common.system.entity.User;
import com.xyrl.project.common.util.XyrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * 自定义实现 ShiroRealm，包含认证和授权两大模块
 *
 * @author MrBird
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserManager userManager;

    /**
     * 是否开启权限校验 默认为true
     */
    @Value("${xyrl.shiro.isAuth:true}")
    private boolean isAuth;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * `
     * 授权模块，获取用户角色和权限
     *
     * @param token token
     * @return AuthorizationInfo 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
        String username = JWTUtil.getUsername(token.toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 获取用户角色集
        Set<String> roleSet = userManager.getUserRoles(username);
        simpleAuthorizationInfo.setRoles(roleSet);
        // 获取用户权限集
        Set<String> permissionSet = null;
        if (isAuth) {
            // 获取用户权限集
            permissionSet = userManager.getUserPermissions(username);
        } else {
            permissionSet = userManager.closeAuthPermissions();
        }
        // 获取用户权限集
        permissionSet = userManager.getUserPermissions(username);
        simpleAuthorizationInfo.setStringPermissions(permissionSet);
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证
     *
     * @param authenticationToken 身份认证 token
     * @return AuthenticationInfo 身份认证信息
     * @throws AuthenticationException 认证相关异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的，已经经过了解密
        String token = (String) authenticationToken.getCredentials();
        if(!isAuth){
            return new SimpleAuthenticationInfo(token, token, "xyrl_shiro_manager_realm");
        }
        // 从 redis里获取这个 token
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        log.info("请求url:{}",request.getServletPath());
        LoginInfo loginInfo=JWTUtil.checkToken(token);
        // 通过用户名查询用户信息
        User user = userManager.getUser(loginInfo.getLoginName());
        if (user == null) {
            throw new AuthenticationException("用户名或密码错误");
        }
        if (!JWTUtil.verify(token, loginInfo, user.getPassword())) {
            throw new AuthenticationException("token校验不通过");
        }
        return new SimpleAuthenticationInfo(token, token, "xyrl_shiro_manager_realm");
    }
}
